package com.deprice4u_client.products_on_sale;

import java.util.ArrayList;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.util.Pair;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import com.deprice4u_client.DrawableManager;
import com.deprice4u_client.R;
import com.deprice4u_client.Tile;
import com.deprice4u_client.image_loader.ImageLoader;


public class SocialTiledUIActivity extends Fragment {
	/** Called when the activity is first created. */

	View v;
	
	LinearLayout llForSubTile;
	
	static boolean SUB_TILE_FRONT = true;
	static boolean SUB_TILE_BACK = false;
	
	public Pair<ArrayList<SocialDataClass>, ArrayList<String>> searchResultPair;
	public ArrayList<SocialDataClass> mItemList;
	
	public ImageLoader imageLoader;


	@Override
	public View onCreateView(LayoutInflater inflater,
	            ViewGroup container, Bundle savedInstanceState) {
		if (container == null) {
            // Currently in a layout without a container, so no
            // reason to create our view.
        	Log.i("SM","container == null");
            return null;
        }

		v = inflater.inflate(R.layout.social_tiled_ui, null);

		//ListView에서 search 결과 받아옴
		SocialListViewActivity fragment = (SocialListViewActivity) getFragmentManager().findFragmentById(R.id.tab_on_sale);
		this.searchResultPair = fragment.searchResultPair;
		if(this.searchResultPair == null){
			return v;
		}
		mItemList = this.searchResultPair.first;
		imageLoader = fragment.adapter.imageLoader;
		
		//각종 뷰 초기화
        
		Display display = getActivity().getWindowManager().getDefaultDisplay();
		SocialOneTile.DISPLAY_WIDTH = display.getWidth();
		
		
		RelativeLayout rl = (RelativeLayout)v.findViewById(R.id.rl_tiled_ui_social);
		rl.setBackgroundColor(Color.BLACK);

		

		
		int numberOfItems = mItemList.size();
		

		ArrayList<SocialOneTile> arry = new ArrayList<SocialOneTile>();
		// Tile 생성하고 정보 입력
		for (int i = 0; i < numberOfItems; i++) {
			SocialOneTile cv = new SocialOneTile(v.getContext());  
			cv.parent = this;
			cv.data = mItemList.get(i);
			arry.add(cv);
		}

		// 각 Tile에 wieght를 입력한다.
		SocialOneTile cv = arry.get(0);
		int weightOfTile = cv.data.price_now;
		int maxWeight = weightOfTile;
		int minWeight = weightOfTile;
		cv.setWeight(weightOfTile);
		for (int i = 1; i < arry.size(); i++) {
			cv = arry.get(i);
			weightOfTile =  cv.data.price_now;
			cv.setWeight(weightOfTile);
			if (weightOfTile > maxWeight)
				maxWeight = weightOfTile;
			if (weightOfTile < minWeight)
				minWeight = weightOfTile;
		}

		// Sorting by weight
		for (int i = 0; i < arry.size(); i++) {
			for (int j = i + 1; j < arry.size(); j++) {
				if (arry.get(i).weight < arry.get(j).weight) {
					SocialOneTile temp = arry.get(i);
					arry.set(i, arry.get(j));
					arry.set(j, temp);
				}
			}
		}

		// id assign
		for (int i = 0; i < arry.size(); i++) {
			arry.get(i).setId(i + 100); // id를 0부터 세팅 하면 이상하게 자꾸 id 0번을 갖는 Tile에
										// 이상이 생겨서 그냥 i+100 해준거임
		}

		int marginSize = 5;

		ArrayList<SocialOneTile> arry3 = new ArrayList<SocialOneTile>();
		ArrayList<SocialOneTile> arry2 = new ArrayList<SocialOneTile>();
		ArrayList<SocialOneTile> arry1 = new ArrayList<SocialOneTile>();

		// level assign
		int numOfBoxInOneLevel = numberOfItems / 4;
		for (int i = 0; i < numOfBoxInOneLevel; i++) {
			arry.get(i).level = 3;
			arry.get(i).calculateSizeOfView(marginSize);
			arry3.add(arry.get(i));
		}
		for (int i = numOfBoxInOneLevel; i < numOfBoxInOneLevel * 2; i++) {
			arry.get(i).level = 2;
			arry.get(i).calculateSizeOfView(marginSize);
			arry2.add(arry.get(i));
		}
		for (int i = numOfBoxInOneLevel * 2; i < arry.size(); i++) {
			arry.get(i).level = 1;
			arry.get(i).calculateSizeOfView(marginSize);
			arry1.add(arry.get(i));
		}

		Log.i("SM", "Begin");

		// LL에 넣어보자
		// 한 stage에 4개의 box가 들어간다
		// stageType에 따라서 4개의 박스가 어떤 형태로 들어가는지 결정된다.
		// StageSubType에 따라서 긴 박스가 가로로 들어갈지 세로로 들어갈지 결정된다.
		int numOfStage = (numberOfItems / Tile.NUM_OF_BOXES_IN_STAGE);
		int stageType = -1;
		int stageSubType = -1; // 0이면 세로 1이면 가로
		int prevStageType = -1;

		for (int i = 0; i < numOfStage; i++) {
			int topMargin = marginSize + i * (arry3.get(0).height + marginSize);
			while (prevStageType == stageType) {
				stageType = (int) ((Math.random() * 100) % 6);
			}
			stageSubType = (int) ((Math.random() * 100) % 2); // 0이면 세로 1이면 가로
			prevStageType = stageType;

			SocialOneTile box3 = arry3.get(i);
			SocialOneTile box2 = arry2.get(i);
			SocialOneTile box11 = arry1.get(2 * i);
			SocialOneTile box12 = arry1.get(2 * i + 1);

			RelativeLayout.LayoutParams lp3 = new RelativeLayout.LayoutParams(
					LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
			RelativeLayout.LayoutParams lp2 = new RelativeLayout.LayoutParams(
					LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
			RelativeLayout.LayoutParams lp11 = new RelativeLayout.LayoutParams(
					LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
			RelativeLayout.LayoutParams lp12 = new RelativeLayout.LayoutParams(
					LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);

		//	Log.i("SM", "stageType : " + String.valueOf(stageType) + "\t subType : " + String.valueOf(stageSubType));
			switch (stageType) {
			case 0:
				lp3.leftMargin = marginSize;
				lp3.topMargin = topMargin;
				rl.addView(box3, lp3);

				if (stageSubType == 0) {
					lp2.addRule(RelativeLayout.RIGHT_OF, box3.getId());
					lp2.leftMargin = marginSize;
					lp2.topMargin = topMargin;
					rl.addView(box2, lp2);

					lp11.addRule(RelativeLayout.RIGHT_OF, box2.getId());
					lp11.leftMargin = marginSize;
					lp11.topMargin = topMargin;
					rl.addView(box11, lp11);

					lp12.addRule(RelativeLayout.RIGHT_OF, box2.getId());
					lp12.addRule(RelativeLayout.BELOW, box11.getId());
					lp12.leftMargin = marginSize;
					lp12.topMargin = marginSize;
					rl.addView(box12, lp12);
				} else {
					box2.width = box11.width * 2 + marginSize;
					box2.height = box11.height;
					lp2.addRule(RelativeLayout.RIGHT_OF, box3.getId());
					lp2.leftMargin = marginSize;
					lp2.topMargin = topMargin;
					rl.addView(box2, lp2);

					lp11.addRule(RelativeLayout.RIGHT_OF, box3.getId());
					lp11.addRule(RelativeLayout.BELOW, box2.getId());
					lp11.leftMargin = marginSize;
					lp11.topMargin = marginSize;
					rl.addView(box11, lp11);

					lp12.addRule(RelativeLayout.RIGHT_OF, box11.getId());
					lp12.addRule(RelativeLayout.BELOW, box2.getId());
					lp12.leftMargin = marginSize;
					lp12.topMargin = marginSize;
					rl.addView(box12, lp12);
				}

				break;
			case 1:
				lp3.leftMargin = marginSize;
				lp3.topMargin = topMargin;
				rl.addView(box3, lp3);

				if (stageSubType == 0) {

					lp11.addRule(RelativeLayout.RIGHT_OF, box3.getId());
					lp11.leftMargin = marginSize;
					lp11.topMargin = topMargin;
					rl.addView(box11, lp11);

					lp12.addRule(RelativeLayout.RIGHT_OF, box3.getId());
					lp12.addRule(RelativeLayout.BELOW, box11.getId());
					lp12.leftMargin = marginSize;
					lp12.topMargin = marginSize;
					rl.addView(box12, lp12);

					lp2.addRule(RelativeLayout.RIGHT_OF, box11.getId());
					lp2.leftMargin = marginSize;
					lp2.topMargin = topMargin;
					rl.addView(box2, lp2);
				} else {
					lp11.addRule(RelativeLayout.RIGHT_OF, box3.getId());
					lp11.leftMargin = marginSize;
					lp11.topMargin = topMargin;
					rl.addView(box11, lp11);

					lp12.addRule(RelativeLayout.RIGHT_OF, box11.getId());
					lp12.leftMargin = marginSize;
					lp12.topMargin = topMargin;
					rl.addView(box12, lp12);

					box2.width = box11.width * 2 + marginSize;
					box2.height = box11.height;
					lp2.addRule(RelativeLayout.RIGHT_OF, box3.getId());
					lp2.addRule(RelativeLayout.BELOW, box11.getId());
					lp2.leftMargin = marginSize;
					lp2.topMargin = marginSize;
					rl.addView(box2, lp2);
				}

				break;
			case 2:
				lp2.leftMargin = marginSize;
				lp2.topMargin = topMargin;
				rl.addView(box2, lp2);

				lp3.addRule(RelativeLayout.RIGHT_OF, box2.getId());
				lp3.leftMargin = marginSize;
				lp3.topMargin = topMargin;
				rl.addView(box3, lp3);

				lp12.addRule(RelativeLayout.RIGHT_OF, box3.getId());
				lp12.leftMargin = marginSize;
				lp12.topMargin = topMargin;
				rl.addView(box12, lp12);

				lp11.addRule(RelativeLayout.RIGHT_OF, box3.getId());
				lp11.addRule(RelativeLayout.BELOW, box12.getId());
				lp11.leftMargin = marginSize;
				lp11.topMargin = marginSize;
				rl.addView(box11, lp11);

				break;
			case 3:
				lp11.leftMargin = marginSize;
				lp11.topMargin = topMargin;
				rl.addView(box11, lp11);

				lp12.addRule(RelativeLayout.BELOW, box11.getId());
				lp12.leftMargin = marginSize;
				lp12.topMargin = marginSize;
				rl.addView(box12, lp12);

				lp3.addRule(RelativeLayout.RIGHT_OF, box11.getId());
				lp3.leftMargin = marginSize;
				lp3.topMargin = topMargin;
				rl.addView(box3, lp3);

				lp2.addRule(RelativeLayout.RIGHT_OF, box3.getId());
				lp2.leftMargin = marginSize;
				lp2.topMargin = topMargin;
				rl.addView(box2, lp2);
				break;
			case 4:
				if (stageSubType == 0) {
					lp2.leftMargin = marginSize;
					lp2.topMargin = topMargin;
					rl.addView(box2, lp2);

					lp11.addRule(RelativeLayout.RIGHT_OF, box2.getId());
					lp11.leftMargin = marginSize;
					lp11.topMargin = topMargin;
					rl.addView(box11, lp11);

					lp12.addRule(RelativeLayout.RIGHT_OF, box2.getId());
					lp12.addRule(RelativeLayout.BELOW, box11.getId());
					lp12.leftMargin = marginSize;
					lp12.topMargin = marginSize;
					rl.addView(box12, lp12);
				} else {
					box2.width = box11.width * 2 + marginSize;
					box2.height = box11.height;
					lp2.leftMargin = marginSize;
					lp2.topMargin = topMargin;
					rl.addView(box2, lp2);

					lp11.addRule(RelativeLayout.BELOW, box2.getId());
					lp11.leftMargin = marginSize;
					lp11.topMargin = marginSize;
					rl.addView(box11, lp11);

					lp12.addRule(RelativeLayout.BELOW, box2.getId());
					lp12.addRule(RelativeLayout.RIGHT_OF, box11.getId());
					lp12.leftMargin = marginSize;
					lp12.topMargin = marginSize;
					rl.addView(box12, lp12);
				}

				lp3.addRule(RelativeLayout.RIGHT_OF, box12.getId());
				lp3.leftMargin = marginSize;
				lp3.topMargin = topMargin;
				rl.addView(box3, lp3);

				break;
			case 5:
				if (stageSubType == 0) {
					lp11.leftMargin = marginSize;
					lp11.topMargin = topMargin;
					rl.addView(box11, lp11);

					lp12.addRule(RelativeLayout.BELOW, box11.getId());
					lp12.leftMargin = marginSize;
					lp12.topMargin = marginSize;
					rl.addView(box12, lp12);

					lp2.addRule(RelativeLayout.RIGHT_OF, box11.getId());
					lp2.leftMargin = marginSize;
					lp2.topMargin = topMargin;
					rl.addView(box2, lp2);
				} else {
					lp11.leftMargin = marginSize;
					lp11.topMargin = topMargin;
					rl.addView(box11, lp11);

					lp12.addRule(RelativeLayout.RIGHT_OF, box11.getId());
					lp12.leftMargin = marginSize;
					lp12.topMargin = topMargin;
					rl.addView(box12, lp12);

					lp2.addRule(RelativeLayout.BELOW, box11.getId());
					box2.width = box11.width * 2 + marginSize;
					box2.height = box11.height;
					lp2.leftMargin = marginSize;
					lp2.topMargin = marginSize;
					rl.addView(box2, lp2);
				}

				lp3.addRule(RelativeLayout.RIGHT_OF, box2.getId());
				lp3.leftMargin = marginSize;
				lp3.topMargin = topMargin;
				rl.addView(box3, lp3);

				break;
			}
		}
		// 한 stage에 4개의 박스가 들어가기 때문에 총 박스의 개수가 4의 배수가 아니면 3개 이하로 박스가 남게 된다.
		// 남은 박스의 사이즈는 가장 작은 사이즈이다.
		// 남은 박스에 대해서 차례로 배치한다.
		for (int j = 0, i = numOfStage * 2; i < arry1.size(); i++, j++) {
			int topMargin = marginSize + numOfStage
					* (arry3.get(0).height + marginSize);
			int leftMargin = marginSize + j * (arry1.get(0).width + marginSize);
			SocialOneTile box = arry1.get(i);
			RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
					LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
			lp.topMargin = topMargin;
			lp.leftMargin = leftMargin;
			rl.addView(box, lp);

		}

		arry.clear();
		for (int i = 0; i < arry3.size(); i++) {
			arry.add(arry3.get(i));
			arry.add(arry2.get(i));
			arry.add(arry1.get(2 * i));  
			arry.add(arry1.get(2 * i + 1));
		}
		for (int i = numOfStage * 2; i < arry1.size(); i++) {
			arry.add(arry1.get(i));
		}
		
		/*for(int i=0; i< arry.size();i++){
			imageLoader.DisplayImage(arry.get(i).data.photo_url, arry.get(i).);
		}*/
		/*DrawableManager dm = new DrawableManager();
		for (int i = 0; i < arry.size(); i++) {
			dm.putImageUrlAndTileOfSocial(arry.get(i).data.photo_url, arry.get(i));
		}
		dm.fetchDrawableOnThreadFromSocial();*/
		for (int i = 0; i < arry.size(); i++) {
			arry.get(i).image = imageLoader.getBitmap(arry.get(i).data.photo_url);
		}
		  
        return v;

	}
	
	public void callSocialDetailView(SocialDataClass data){
		// 다음 액티비티로 넘길 Bundle 데이터를 만든다.
				Bundle extras = new Bundle();
				extras.putString("title", data.title);
				extras.putString("link", data.link);
				extras.putString("time_start", data.time_start);
				extras.putString("time_end", data.time_end);
				extras.putInt("price_original", data.price_original);
				extras.putInt("price_now", data.price_now);
				extras.putString("social_provider", data.social_provider);
				extras.putString("area", data.area);
				extras.putString("photo_url", data.photo_url);

				// 인텐트를 생성한다.
				// 컨텍스트로 현재 액티비티를, 생성할 액티비티로 ItemClickExampleNextActivity 를 지정한다.
				Intent intent = new Intent(v.getContext(), SocialDetailActivity.class);

				// 위에서 만든 Bundle을 인텐트에 넣는다.
				intent.putExtras(extras);

				// 액티비티를 생성한다.
				v.getContext().startActivity(intent);
	}

	
	
}
